package com.chookss.home.logContacts;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.publish.PublishLogsActivity;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.Utils;
import com.chookss.view.DrawableTextView;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.consecutivescroller.ConsecutiveNoScrollViewPager;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

@SuppressLint("ValidFragment")
public class LookLogBaseFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.title_back)
    LinearLayout title_back;
    @BindView(R.id.llAllLogs)
    LinearLayout llAllLogs;
    @BindView(R.id.lookLogRightll)
    LinearLayout lookLogRightll;
    @BindView(R.id.llGroups)
    LinearLayout llGroups;
    @BindView(R.id.llMyLogs)
    LinearLayout llMyLogs;
    @BindView(R.id.llChoice)
    LinearLayout llChoice;
    @BindView(R.id.viewPager)
    ConsecutiveNoScrollViewPager viewPager;
    @BindView(R.id.rlDayLog)
    DrawableTextView rlDayLog;
    @BindView(R.id.rlDaily)
    DrawableTextView rlDaily;
    @BindView(R.id.rlWeekly)
    DrawableTextView rlWeekly;
    @BindView(R.id.rlMonthly)
    DrawableTextView rlMonthly;
    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tvAll)
    TextView tvAll;
    @BindView(R.id.rlMore)
    RelativeLayout rlMore;
    @BindView(R.id.rvMore)
    RecyclerView rvMore;
    private MyAdapter pagerAdapter;
    private LogFragment logFragment0;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ArrayList<String> typeList = new ArrayList<>();
    private int position = 0;//默认选择全部日志1我的日志
    private int type = 0; //0一级页面没有返回1是activity要返回
    private String reportType = "";// 0 日报 1 周报 2 月报 3 日志
    private String startTime = "", endTime = "";
    private List<ContactEntity> selectList = new ArrayList<>();

    public LookLogBaseFragment() {

    }

    public LookLogBaseFragment(int type) {
        this.type = type;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_look_log, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        //顶部状态栏 处理
        NavigationTools.saveUseRecord(mContext,"1","02");
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            statusBar.setVisibility(View.VISIBLE);
            title_back.setVisibility(View.GONE);
            tvTitle.getPaint().setFakeBoldText(true);
        } else {
            statusBar.setVisibility(View.GONE);
            title_back.setVisibility(View.VISIBLE);
        }
        logFragment0 = new LogFragment("0");
        fragments.add(logFragment0);
        fragments.add(new LogGroupFragment());
        fragments.add(new LogFragment("1"));
        pagerAdapter = new MyAdapter(getChildFragmentManager(), fragments);
        viewPager.setAdapter(pagerAdapter);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout r) {
                // 把加载的动作传给当初的fragment
                if (viewPager == null) {
                    return;
                }
                if (position == 1) {
                    LogGroupFragment fragment = (LogGroupFragment) pagerAdapter.getItem(viewPager.getCurrentItem());
                    fragment.onLoadMore(refreshLayout);
                } else {
                    LogFragment fragment = (LogFragment) pagerAdapter.getItem(viewPager.getCurrentItem());
                    fragment.onLoadMore(refreshLayout);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout r) {
                if (viewPager == null) {
                    return;
                }
                if (position == 1) {
                    LogGroupFragment fragment = (LogGroupFragment) pagerAdapter.getItem(viewPager.getCurrentItem());
                    fragment.onRefresh(refreshLayout);
                } else {
                    LogFragment fragment = (LogFragment) pagerAdapter.getItem(viewPager.getCurrentItem());
                    fragment.onRefresh(refreshLayout);
                }

            }
        });
        viewPager.setOffscreenPageLimit(2);
        llChoice.post(new Runnable() {
            @Override
            public void run() {
                if (viewPager == null) {
                    return;
                }
                viewPager.setAdjustHeight(llChoice.getHeight());
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int positions) {
                position = positions;
                changeUi();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        refreshLayout.autoRefresh();
        changeUi();
        typeList.add("查找日志");
        typeList.add("编辑分组");
        rvMore.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rvMore.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        TypeAdapter adapter = new TypeAdapter(R.layout.item_looklog_type, mContext, typeList);
        rvMore.setAdapter(adapter);
        MyApp.contactEntityLogList.clear();
    }

    class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(@NonNull FragmentManager fm, List<Fragment> fragments) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    private void changeUi() {
        if (llAllLogs == null) {
            return;
        }
        viewPager.setCurrentItem(position);
        if (position == 0) {
            llAllLogs.getChildAt(0).setSelected(true);
            llAllLogs.getChildAt(1).setVisibility(View.VISIBLE);
            llGroups.getChildAt(0).setSelected(false);
            llGroups.getChildAt(1).setVisibility(View.INVISIBLE);
            lookLogRightll.setVisibility(View.VISIBLE);
            llMyLogs.getChildAt(0).setSelected(false);
            llMyLogs.getChildAt(1).setVisibility(View.INVISIBLE);
        } else if (position == 1) {
            llAllLogs.getChildAt(0).setSelected(false);
            llAllLogs.getChildAt(1).setVisibility(View.INVISIBLE);
            llGroups.getChildAt(0).setSelected(true);
            llGroups.getChildAt(1).setVisibility(View.VISIBLE);
            lookLogRightll.setVisibility(View.VISIBLE);
            llMyLogs.getChildAt(0).setSelected(false);
            llMyLogs.getChildAt(1).setVisibility(View.INVISIBLE);
        } else {
            llAllLogs.getChildAt(0).setSelected(false);
            llAllLogs.getChildAt(1).setVisibility(View.INVISIBLE);
            llGroups.getChildAt(0).setSelected(false);
            llGroups.getChildAt(1).setVisibility(View.INVISIBLE);
            lookLogRightll.setVisibility(View.GONE);
            llMyLogs.getChildAt(0).setSelected(true);
            llMyLogs.getChildAt(1).setVisibility(View.VISIBLE);
        }
    }


    class TypeAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;

        public TypeAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable ArrayList<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvType = helper.getView(R.id.tvType);
            tvType.setText(entity);
            tvType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rlMore.setVisibility(View.GONE);
                    if (helper.getItemPosition() == 0) {
                        Intent intent = new Intent(mContext, LogChoiceActivity.class);
                        intent.putExtra("reportType", reportType);
                        intent.putExtra("startTime", startTime);
                        intent.putExtra("endTime", endTime);
                        intent.putExtra("selectList", (Serializable) selectList);
                        mContext.startActivityForResult(intent, 1);
                        if (position == 1) {
                            Observable.timer(1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) {
                                    viewPager.setCurrentItem(0);
                                }
                            });
                        }
                    } else {
                        Intent intent1 = new Intent(mContext, LogManagersActivity.class);
                        mContext.startActivity(intent1);
                        if (position == 0) {
                            Observable.timer(1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) {
                                    viewPager.setCurrentItem(1);
                                }
                            });
                        }
                    }

                }
            });
        }
    }

    @OnClick({R.id.title_back, R.id.rlMore, R.id.lookLogRightll, R.id.llAllLogs, R.id.llGroups, R.id.llMyLogs, R.id.rlDayLog, R.id.rlDaily, R.id.rlWeekly, R.id.rlMonthly})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.title_back:
                if (mContext != null) {
                    mContext.finish();
                }
                break;
            case R.id.lookLogRightll:
                if (rlMore == null) {
                    return;
                }
                if (rlMore.getVisibility() == View.VISIBLE) {
                    rlMore.setVisibility(View.GONE);
                } else {
                    rlMore.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rlMore:
                if (rlMore == null) {
                    return;
                }
                rlMore.setVisibility(View.GONE);
                break;
            case R.id.llAllLogs:
                position = 0;
                changeUi();
                break;
            case R.id.llGroups:
                position = 1;
                changeUi();
                break;
            case R.id.llMyLogs:
                position = 2;
                changeUi();
                break;
            case R.id.rlDayLog:
                if (PermissionSpUtils.getBoolean(mContext,"12",false)) {
                    intent = new Intent(mContext, PublishLogsActivity.class);
                    intent.putExtra("type", 3);
                    mContext.startActivity(intent);
                } else {
                    MyToast.show("管理员已关闭日志发布功能");
                }

                break;
            case R.id.rlDaily:
                if (PermissionSpUtils.getBoolean(mContext,"21",false)) {
                    intent = new Intent(mContext, PublishLogsActivity.class);
                    intent.putExtra("type", 0);
                    mContext.startActivity(intent);
                } else {
                    MyToast.show("管理员已关闭日报发布功能");
                }
                break;
            case R.id.rlWeekly:
                if (PermissionSpUtils.getBoolean(mContext,"22",false)) {
                    intent = new Intent(mContext, PublishLogsActivity.class);
                    intent.putExtra("type", 1);
                    mContext.startActivity(intent);
                } else {
                    MyToast.show("管理员已关闭周报发布功能");
                }
                break;
            case R.id.rlMonthly:
                if (PermissionSpUtils.getBoolean(mContext,"23",false)) {
                    intent = new Intent(mContext, PublishLogsActivity.class);
                    intent.putExtra("type", 2);
                    mContext.startActivity(intent);
                } else {
                    MyToast.show("管理员已关闭月报发布功能");
                }
                break;
        }

    }

    public void setOnActivityResult(String startTime, String endTime, String reportType, List<ContactEntity> selectList) {
        this.selectList.clear();
        this.startTime = startTime;
        this.endTime = endTime;
        this.reportType = reportType;
        this.selectList = selectList;
        logFragment0.refreshData(startTime, endTime, reportType, selectList);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
